package com.xmqian.app.project.ui.preview.activity

import android.Manifest
import android.content.Intent
import android.graphics.Typeface
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.coszero.common.config.RequestCode
import com.coszero.common.utils.glide.ImageLoad
import com.coszero.common.utils.matisse.SelectImageUtils
import com.coszero.common.utils.permission.PermissionHelper
import com.coszero.common.utils.permission.PermissionHelper.CallBackFail
import com.coszero.common.utils.xpopup.XPopupUtils
import com.coszero.ui.dialog.ToastUtils
import com.coszero.utils.media.SoundPoolUtils
import com.coszero.utils.utils.LogX
import com.coszero.utils.utils.StringUtils
import com.example.xmqian.R
import com.example.xmqian.databinding.ActivityTestRunBinding
import com.lxj.xpopup.core.BasePopupView
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.xmqian.app.project.common.apiadapter.NotificationChannelUtils
import com.xmqian.app.project.common.base.BaseMyActivity
import com.xmqian.app.project.common.testdata.TestUtils
import com.xmqian.app.project.dialog.ChoosePictureDialog
import com.xmqian.app.project.dialog.ChoosePictureDialog.ChoosePictureCallBack
import com.xmqian.app.project.event.LoginEvent
import com.xmqian.app.project.ui.common.activity.MyWebViewActivity
import com.xmqian.app.project.ui.main.MainActivity
import com.xmqian.app.project.ui.main.MainBottomTabActivity
import com.xmqian.app.project.ui.user.activity.LoginActivity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.util.Arrays

/**
 * Desc： 主页
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2025/4/16
 */
class TestMainActivity : BaseMyActivity() {
    private var lastPressBackKeyTime: Long = 0
    private var testUtils: TestUtils? = null
    var smartRefreshLayout: SmartRefreshLayout? = null
    var mIvImage: ImageView? = null
    private var takePhotoPath: String?=null
    private var permissionHelper: PermissionHelper? = null

    /**
     * 相机照片路径
     */
    private var cameraPath: String? = null
    private var poolUtils: SoundPoolUtils? = null
    private var binding: ActivityTestRunBinding? = null

    override fun getLayoutView(): View {
        setDisplayFullScreen()
        binding = ActivityTestRunBinding.inflate(layoutInflater)
        setStatusBarPadding(binding!!.lvList)
        return binding!!.root
    }

    // <editor-fold desc="生命周期" defaultstate="collapsed">
    override fun initView() {
        smartRefreshLayout = binding!!.refreshLayout
        mIvImage = binding!!.ivImage


        smartRefreshLayout!!.setOnRefreshListener { refreshlayout: RefreshLayout ->
            refreshlayout.finishRefresh(2000 /*,false*/) //传入false表示刷新失败
        }
        smartRefreshLayout!!.setOnLoadMoreListener { refreshlayout: RefreshLayout ->
            refreshlayout.finishLoadMore(2000 /*,false*/) //传入false表示加载失败
        }
        testUtils = TestUtils.newInstance(this)
        val stringArray = resources.getStringArray(R.array.item_name)
        val items = Arrays.asList(*stringArray)
        val listView = findViewById<ListView>(R.id.lv_list)
        listView.adapter =
            object : ArrayAdapter<Any?>(this, android.R.layout.simple_list_item_1,
                items as List<Any?>
            ) {
                override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                    val textView = TextView(context)
                    textView.text = items[position]
                    textView.textSize = 16f
                    textView.setBackgroundColor(-0x66000001)
                    textView.setPadding(0, 30, 0, 30)
                    textView.gravity = Gravity.CENTER
                    textView.typeface = Typeface.DEFAULT_BOLD
                    return textView
                }
            }
        listView.onItemClickListener =
            AdapterView.OnItemClickListener { parent: AdapterView<*>?, view: View?, position: Int, id: Long ->
                use(
                    position
                )
            }
        //初始化渠道通知，8.0+
        NotificationChannelUtils.newInstance(this).init()
    }

    override fun initData() {
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //        permissionHelper.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                TestUtils.REQUEST_TAKE_PHOTO_CODE ->                     //相机
                    if (!StringUtils.isEmpty(cameraPath)) {
                        val file = File(cameraPath)
                        LogX.i(
                            """### 拍摄照片后的路径：$cameraPath
 文件大小：${file.length()}"""
                        )
                        ImageLoad.loadImage(this, cameraPath, mIvImage)
                    }

                SelectImageUtils.REQUEST_CODE_CHOOSE -> {
                    val imagePaths = SelectImageUtils.getImagePaths(data)
                    val s = imagePaths[0]
                    ImageLoad.loadImage(this, s, mIvImage)
                }

                SelectImageUtils.REQUEST_CODE_CHOOSE_PHOTO_SHOOT -> {
                    val takePhotoFile = SelectImageUtils.getTakePhotoFile(takePhotoPath)
                    ImageLoad.loadImage(this, takePhotoFile, mIvImage)
                }
            }
        }
    }

    //</editor-fold>
    private fun use(pos: Int) {
        when (pos) {
            0 -> {
                val alertDialog = AlertDialog.Builder(this)
                alertDialog.setTitle("温馨提示")
                    .setMessage("申请相机，读写，定位权限")
                    .setPositiveButton(
                        "确定开启"
                    ) { dialog, which ->
                        PermissionHelper.requestEasy(
                            this@TestMainActivity,
                            object : CallBackFail {
                                override fun requestFail() {
                                    ToastUtils.showMsg("权限申请失败")
                                }

                                override fun requestSuccess() {
                                    ToastUtils.showLongMsg("权限申请成功")
                                }
                            })
                    }.show()
            }

            1 -> {
                permissionHelper = PermissionHelper()
                permissionHelper!!.requestActivity(
                    mActivity, Manifest.permission.CAMERA, RequestCode.REQUEST_PERMISSION_CODE
                ) { cameraPath = testUtils!!.takePhoto() }
            }

            2 -> {
                NotificationChannelUtils.newInstance(this).sendMessage()
                LogX.d("### 通知渠道 ---使用自定义jar")
            }

            3 -> LoginActivity.startTask(this)
            4 -> startActivity(
                MyWebViewActivity.getIntent(
                    this,
                    "通用网页",
                    "https://www.baidu.com"
                )
            )

            5 -> {
                val xPopupUtils = XPopupUtils(this)
                xPopupUtils.init<BasePopupView>(
                    ChoosePictureDialog(
                        this,
                        object : ChoosePictureCallBack {
                            override fun selectGallery() {
                                SelectImageUtils.selectSingleImage(this@TestMainActivity)
                            }

                            override fun selectCapture() {
                                SelectImageUtils.takePhoto(
                                    this@TestMainActivity
                                ) { path: String? ->
                                    takePhotoPath = path
                                }
                            }
                        })
                ).show()
            }

            6 -> MainActivity.startActivity(mActivity)
            7 -> MainBottomTabActivity.startTask(mActivity)
            8 -> {
                //播放短促音频
                if (poolUtils == null) {
                    poolUtils = SoundPoolUtils(this)
                }
                poolUtils!!.playSoundWithRedId(R.raw.barcodebeep)
                //播放长音频
//                MediaPlayerUtils.playAdudio(this, R.raw.tip_network_and_request_faile_please_try_again);
                LogX.i("播放音频文件")
            }

            9 -> PagePreviewActivity.startActivity(mActivity)
            else -> {}
        }
    }

    private fun showWaringDialog() {
        val dialog = AlertDialog.Builder(this)
            .setTitle("警告！")
            .setMessage("请前往设置->应用->" + getString(R.string.app_name) + "->权限中打开相关权限，否则功能无法正常运行！")
            .setPositiveButton("确定") { dialog, which ->
                // 一般情况下如果用户不授权的话，功能是无法运行的，做退出处理
                //                        finish();
            }.show()
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
            super.onBackPressed()
        } else {
            lastPressBackKeyTime = System.currentTimeMillis()
            ToastUtils.showLongMsg(resources.getString(R.string.toast_press_again_exit_app))
        }
    }

    /*@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
                return super.onKeyDown(keyCode, event);
            } else {
                lastPressBackKeyTime = System.currentTimeMillis();
                ToastUtils.showLongMsg(getResources().getString(R.string.toast_press_again_exit_app));
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventLogin(event: LoginEvent) {
        if (event.isLogin) {
            LogX.i("### 登录成功")
        } else {
            LogX.i("### 退出登录成功")
        }
    }

    companion object {
        /**
         * 退出间隔时间
         */
        private const val DELAY_TIME: Long = 1500
    }
}
